package com.jinlejia.erp.ui.customer;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.ddm.library.DropDownMenu;
import com.freedom.yefeng.yfrecyclerview.YfListMode;
import com.freedom.yefeng.yfrecyclerview.YfLoadMoreListener;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.HouseSelectAdapter;
import com.jinlejia.erp.adapter.ListMapDropDownAdapter;
import com.jinlejia.erp.adapter.SelectRentAdapter;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.common.RecycleViewDivider;
import com.jinlejia.erp.databinding.ActivityAddHouseBinding;
import com.jinlejia.erp.ui.house.MenuMoreActivity;
import com.jinlejia.erp.ui.house.SearchHouseActivity;
import com.jinlejia.erp.utils.ActivityCollector;
import com.jinlejia.erp.utils.DataFilter;
import com.weight.CustomToast;
import com.zhy.http.okhttp.OkHttpUtils;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

/**
 * 买卖房源
 */
public class AddHouseActivity extends AppCompatActivity implements YfLoadMoreListener {

    private String headers[] = {"全部房源", "价格区间", "居室", "更多"};
    private List<View> popupViews = new ArrayList<>();
    private ListMapDropDownAdapter houseMenuAdapter;
    private ListMapDropDownAdapter roomMenuAdapter;
    private ListMapDropDownAdapter priceMenuAdapter;

    private HouseSelectAdapter shsAdapter;
    private SelectRentAdapter rentAdapter;

    JSONObject jsonObject = new JSONObject();
    private int page = 1;
    private boolean mLoadingLock = false;
    ArrayList<Map<String, Object>> houseTypeList = new ArrayList<>();
    ArrayList<Map<String, Object>> roleList = new ArrayList<>();
    ArrayList<Map<String, Object>> salePriceList = new ArrayList<>();
//    private List<Object> checked = new ArrayList<>();
    private int segmentIndex = 0;
    private HashSet<String> IDs = new HashSet<>();
    private ArrayList<String> moreSelectList = new ArrayList<>();
    private String jsonString;
    private ArrayList<Map<String, Object>> oldDataList = new ArrayList<>();
    private ArrayList<Map<String, Object>> selectDataList = new ArrayList<>();
    private ActivityAddHouseBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_add_house);
        binding.setEvent(this);
        ActivityCollector.addActivity(this);
        if (getIntent().hasExtra("ids")) {
            IDs.addAll(  new HashSet<String>(getIntent().getStringArrayListExtra("ids")) );
        }

        if (getIntent().getStringExtra("type").equals("sale") || getIntent().getStringExtra("type").equals("1")) {
            segmentIndex = 0;
            binding.title.setText("出售");
        } else {
            segmentIndex = 1;
            binding.title.setText("出租");
        }

        if (getIntent().hasExtra("oldData")) {
            ArrayList<Map<String, Object>> oldData = JSON.parseObject(getIntent().getStringExtra("oldData"), new TypeReference<ArrayList<Map<String, Object>>>() {
            });
            for ( Map<String, Object> map : oldData ) {
                Map<String,Object> m = new HashMap<>();
                if( map.containsKey("rsCode") ) {
                    m.put("rscode", map.get("rsCode"));
                }else if( map.containsKey("rscode") ){
                    m.put("rscode", map.get("rscode"));
                }
                m.put("image",map.get("imgUrl"));
                m.put("estate",map.get("estate"));
                m.put("bussiness","");
                m.put("houseType",map.get("shsHouseType"));
                m.put("square",map.get("square"));
                if( segmentIndex == 1 ){
                    m.put("rentPrice",map.get("price"));
                }
                if( segmentIndex == 1 ){
                    m.put("salePrice",map.get("price"));
                    DecimalFormat df = new DecimalFormat("#.00");
                    m.put("unitPrice",df.format( Double.parseDouble(map.get("price").toString()) / Double.parseDouble(map.get("square").toString())* 10000 ));
                }
                oldDataList.add(m);
            }

        }

        EventBus.getDefault().register(this);
        initView();

        if (segmentIndex == 0) {
            getData();
            getHeadDictionary("shs");
        } else {
            getRentData();
            getHeadDictionary("rent");
        }
    }


    @Override
    public void onStart() {
        super.onStart();

    }

    private void initView() {
        //房源菜单 menu
        final ListView houseView = new ListView(this);
        houseMenuAdapter = new ListMapDropDownAdapter(this, roleList);
        houseView.setDivider(this.getResources().getDrawable(R.drawable.shape_h_line));
        houseView.setAdapter(houseMenuAdapter);
        //房源点击
        houseView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                houseMenuAdapter.setCheckItem(position);
                binding.dropDownMenu.setTabText(position == 0 ? headers[0] : roleList.get(position).get("valueName").toString());
                binding.dropDownMenu.closeMenu();
                if( position == 0 ){
                    jsonObject.remove("flag");
                }else {
                    jsonObject.put("flag", roleList.get(position).get("valuel").toString());
                }
                if (segmentIndex == 0) {
                    getData();
                } else {
                    getRentData();
                }
            }
        });

        //价格区间
        final View priceAreaFooter = this.getLayoutInflater().inflate(R.layout.selling_price_area_footer, null);
        final ListView priceAreaView = new ListView(this);
        priceMenuAdapter = new ListMapDropDownAdapter(this, salePriceList);
        priceAreaView.setDivider(this.getResources().getDrawable(R.drawable.shape_h_line));
        priceAreaView.addFooterView(priceAreaFooter);
        priceAreaView.setAdapter(priceMenuAdapter);
        //价格输入框
        final EditText leftPrice = priceAreaFooter.findViewById(R.id.et_left);
        final EditText rightPrice = priceAreaFooter.findViewById(R.id.et_right);
        //重置、确定按钮
        TextView cancel = priceAreaFooter.findViewById(R.id.bt_cancel);
        TextView confirm = priceAreaFooter.findViewById(R.id.bt_confirm);
        //价格列表点击
        priceAreaView.setOnItemClickListener((parent, view, position, id) -> {
            priceMenuAdapter.setCheckItem(position);
            binding.dropDownMenu.setTabText(position == 0 ? headers[1] : salePriceList.get(position).get("valueName").toString());
            binding.dropDownMenu.closeMenu();

            if (segmentIndex == 0) {
                if (position == 0) {
                    jsonObject.remove("salePrice_start");
                    jsonObject.remove("salePrice_end");
                }else {
                    jsonObject.put("salePrice_start", salePriceList.get(position).get("minValue").toString());
                    jsonObject.put("salePrice_end", salePriceList.get(position).get("maxValue").toString());
                }
                getData();
            } else {
                if (position == 0) {
                    jsonObject.remove("rentPrice_start");
                    jsonObject.remove("rentPrice_end");
                }else {
                    jsonObject.put("rentPrice_start", salePriceList.get(position).get("minValue").toString());
                    jsonObject.put("rentPrice_end", salePriceList.get(position).get("maxValue").toString());
                }
                getRentData();
            }
        });
        //点击重置
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                leftPrice.setText("");
                rightPrice.setText("");
            }
        });
        //确定按钮
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(leftPrice.getText().toString())) {
                    Toast.makeText(AddHouseActivity.this, "请输入最低价格", Toast.LENGTH_SHORT).show();
                } else if (TextUtils.isEmpty(rightPrice.getText().toString())) {
                    Toast.makeText(AddHouseActivity.this, "请输入最高价格", Toast.LENGTH_SHORT).show();
                } else {
                    binding.dropDownMenu.setTabText(leftPrice.getText().toString().concat("万-").concat(rightPrice.getText().toString()).concat("万"));
                    binding.dropDownMenu.closeMenu();
                    jsonObject.put("salePrice_start", leftPrice.getText().toString());
                    jsonObject.put("salePrice_end", rightPrice.getText().toString());
                    if (segmentIndex == 0) {
                        getData();
                    } else {
                        getRentData();
                    }
                }
            }
        });


        //  居室
        final ListView roomView = new ListView(this);
        roomMenuAdapter = new ListMapDropDownAdapter(this, houseTypeList);
        roomView.setDivider(this.getResources().getDrawable(R.drawable.shape_h_line));
        roomView.setAdapter(roomMenuAdapter);
        //居室点击
        roomView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                roomMenuAdapter.setCheckItem(position);
                binding.dropDownMenu.setTabText(position == 0 ? headers[2] : houseTypeList.get(position).get("valueName").toString());
                binding.dropDownMenu.closeMenu();
                if( position == 0 ){
                    jsonObject.remove("houseType");
                }else {
                    jsonObject.put("houseType", houseTypeList.get(position).get("valuel").toString());
                }
                if (segmentIndex == 0) {
                    getData();
                } else {
                    getRentData();
                }
            }
        });


        //  更多
        final View moreView = new View(this);

        // 添加到view List
        popupViews.add(houseView);
        popupViews.add(priceAreaView);
        popupViews.add(roomView);
        popupViews.add(moreView);


        TextView contentView = new TextView(this);
        contentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0));
        contentView.setGravity(Gravity.CENTER);
//        contentView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);

        //init dropdownview
        binding.dropDownMenu.setDropDownMenu(Arrays.asList(headers), popupViews, contentView);
        binding.dropDownMenu.setOnMenuChangeListener(new DropDownMenu.OnMenuChangeListener() {
            @Override
            public void onMenuChange(int menuID) {
                if (menuID == 6) {
                    //更多
                    binding.dropDownMenu.closeMenu();
                    Intent intent = new Intent(AddHouseActivity.this, MenuMoreActivity.class);
                    if (segmentIndex == 0) {
                        intent.putExtra("type", "shs");
                    } else {
                        intent.putExtra("type", "rent");
                    }
                    intent.putStringArrayListExtra("selectList",moreSelectList);
                    intent.putExtra("jsonString",jsonString);
                    startActivityForResult(intent,100);
                }
            }
        });

        binding.rvHouseList.setLayoutManager(new LinearLayoutManager(this));
        binding.rvHouseList.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.VERTICAL, 2, getResources().getColor(R.color.colorDivider)));
        binding.rvHouseList.setHasFixedSize(true);
        binding.rvHouseList.enableAutoLoadMore(this);
        ArrayList<Map<String, Object>> dataList = new ArrayList<>();
        shsAdapter = new HouseSelectAdapter(dataList, "CHECK");
        rentAdapter = new SelectRentAdapter(dataList, "CHECK");
        if (segmentIndex == 0) {
            binding.rvHouseList.setAdapter(shsAdapter);
            shsAdapter.changeMode(YfListMode.MODE_LOADING);
        } else {
            binding.rvHouseList.setAdapter(rentAdapter);
            rentAdapter.changeMode(YfListMode.MODE_LOADING);
        }

        binding.rvHouseList.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.VERTICAL, 2, getResources().getColor(R.color.colorDivider)));
        shsAdapter.setOnDefaultListiner(map -> selectDataList.add(map));
        shsAdapter.setSelectHouseID(IDs);
        rentAdapter.setOnDefaultListiner(map -> {
//                checked = Arrays.asList(selectMap.keySet().toArray());
            selectDataList.add(map);
        });
        shsAdapter.setOnSelectedListiner(selectMap -> {
            IDs.add(selectMap.get("rscode").toString());
            binding.btHasCheck.setText("已选房源(" + IDs.size()  + ")");
            selectDataList.add(selectMap);
        });
        rentAdapter.setOnSelectedListiner(selectMap -> {
            IDs.add(selectMap.get("rscode").toString());
            binding.btHasCheck.setText("已选房源(" + IDs.size()  + ")");
            selectDataList.add(selectMap);
        });
        shsAdapter.setOnRemoveListiner(map -> {
            if( IDs.contains(map.get("rscode").toString()) ){
                IDs.remove(map.get("rscode").toString());
            }
            binding.btHasCheck.setText("已选房源(" + IDs.size()  + ")");
            if( selectDataList.contains(map) ){
                selectDataList.remove(map);
            }
            removeOld(map.get("rscode").toString());
        });
        rentAdapter.setOnRemoveListiner(map -> {
            if( IDs.contains(map.get("rscode").toString()) ){
                IDs.remove(map.get("rscode").toString());
            }
            binding.btHasCheck.setText("已选房源(" + IDs.size()  + ")");
            if( selectDataList.contains(map) ){
                selectDataList.remove(map);
            }
            removeOld(map.get("rscode").toString());
        });

        //编辑时，已选房源个数
        if (IDs != null) {
            binding.btHasCheck.setText("已选房源(" + IDs.size() + ")");
            shsAdapter.setSelectHouseID(IDs);
            rentAdapter.setSelectHouseID(IDs);
        }
    }
    private void removeOld( String id ){
        for( int i=0;i<oldDataList.size();i++ ){
            if( oldDataList.get(i).get("rscode").toString().equals(id) ){
                oldDataList.remove(i);
                break;
            }
        }
    }

    private void getData() {
        mLoadingLock = true;
        jsonObject.put("pageSize", 20);
        jsonObject.put("pageIndex", page);
        OkHttpUtils.postString()
                .url(ApiConfig.Sell_HOUSE_LIST)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(AddHouseActivity.this, response, shsAdapter)) {
                            JSONObject data = JSON.parseObject(response.get("data").toString());
                            //数据列表
                            ArrayList<Map<String, Object>> list = JSON.parseObject(data.getJSONArray("list").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            if (page == 1) {
                                shsAdapter.setData(list);
                            } else {
                                shsAdapter.addData(list);
                            }
                            shsAdapter.setSelectHouseID(IDs);
                        } else if (response.get("code").toString().equals("303")) {
                            //没有更多
                            page--;
                        }
                        if (shsAdapter.getFooters().size() > 0)
                            shsAdapter.removeAllFooters();
                        mLoadingLock = false;
                    }
                });
    }

    private void getRentData() {
        mLoadingLock = true;
        jsonObject.put("pageSize", 20);
        jsonObject.put("pageIndex", page);
        OkHttpUtils.postString()
                .url(ApiConfig.RENT_HOUSE_LIST)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(AddHouseActivity.this, response, rentAdapter)) {
                            JSONObject data = JSON.parseObject(response.get("data").toString());
                            //数据列表
                            ArrayList<Map<String, Object>> list = JSON.parseObject(data.getJSONArray("list").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            if (page == 1) {
                                rentAdapter.setData(list);
                            } else {
                                rentAdapter.addData(list);
                            }
                            rentAdapter.setSelectHouseID(IDs);
                        } else if (response.get("code").toString().equals("303")) {
                            //没有更多
                            page--;
                        } else if (response.get("code").toString().equals("501")){
                            //没有数据
                            if (rentAdapter != null)
                                rentAdapter.changeMode(YfListMode.MODE_EMPTY);
                            jsonObject.clear();
                        }
                        if (rentAdapter.getFooters().size() > 0)
                            rentAdapter.removeAllFooters();
                        mLoadingLock = false;
                    }
                });
    }

    @Override
    public void loadMore() {
        if (segmentIndex == 0) {
            if (shsAdapter.getData().size() % 20 == 0) {
                if (mLoadingLock) {
                    return;
                }
                mLoadingLock = true;
                page++;
                shsAdapter.addFooter("loading");
                getData();
            }
        } else {
            if (rentAdapter.getData().size() % 20 == 0) {
                if (mLoadingLock) {
                    return;
                }
                mLoadingLock = true;
                page++;
                rentAdapter.addFooter("loading");
                getRentData();
            }
        }
    }

    private void getHeadDictionary(String type) {

        OkHttpUtils.get()
                .url(ApiConfig.HOUSE_HEAD_DICTIONARY.concat(type))
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(AddHouseActivity.this, response)) {
                            JSONObject data = JSON.parseObject(response.get("data").toString());
                            if (data.containsKey("houseTypeList"))
                                houseTypeList = JSON.parseObject(data.getJSONArray("houseTypeList").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                                });
                            if (data.containsKey("roleList"))
                                roleList = JSON.parseObject(data.getJSONArray("roleList").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                                });
                            if (data.containsKey("salePriceList"))
                                salePriceList = JSON.parseObject(data.getJSONArray("salePriceList").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                                });
                            if( data.containsKey("rentPriceList") )
                                salePriceList = JSON.parseObject(data.getJSONArray("rentPriceList").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                                });
                            houseMenuAdapter.setData(roleList);
                            roomMenuAdapter.setData(houseTypeList);
                            priceMenuAdapter.setData(salePriceList);
                        }
                    }
                });
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_has_check:
                ArrayList<Map<String, Object>> data = new ArrayList<>();
                data.addAll(selectDataList);

                if( data.size()>0 ) {
                    EventBus.getDefault().postSticky(data, "TAG_HAS_CHECKED");
                    Intent intent = new Intent(AddHouseActivity.this, HasChectedActivity.class);
                    if (getIntent().hasExtra("addEnjoy")) {
                        intent.putExtra("addEnjoy", true);
                        intent.putExtra("csCode", getIntent().getStringExtra("csCode"));
                        intent.putExtra("type", getIntent().getStringExtra("type"));
                    }
                    startActivity(intent);
                }else{
                    CustomToast.showToast(AddHouseActivity.this,"请先选房源",1500);
                }
                break;
            case R.id.bt_back:
                finish();
                break;
            case R.id.bt_search:
                Intent intent1 = new Intent(AddHouseActivity.this, SearchHouseActivity.class);
                switch (segmentIndex) {
                    case 0:
                        // 出售
                        intent1.putExtra("type", "shs");
                        startActivity(intent1);
                        break;
                    case 1:
                        //出租
                        intent1.putExtra("type", "rent");
                        startActivity(intent1);
                        break;
                    default:
                        break;
                }
                break;
        }
    }
    @Subscriber(tag = "TAG_SEARCH_RENT")
    public void data( String name ){
        jsonObject.put("key",name);
        page = 1;
        getRentData();
    }
    @Subscriber(tag = "TAG_SEARCH_SHS")
    public void dataShs(String name) {
        jsonObject.put("key", name);
        page = 1;
        getData();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if( resultCode == Activity.RESULT_OK && requestCode == 100){
            jsonString = data.getStringExtra("jsonString");
            moreSelectList = data.getStringArrayListExtra("selectList");
            JSONObject object = JSONObject.parseObject(jsonString);
            if( object.size()>0 ) {
                jsonObject.putAll(object);
            }else{
                jsonObject.clear();
            }
            page = 1;
            if (data.getStringExtra("type").equals("shs")){
                getData();
            }else {
                getRentData();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollector.removeActivity(this);
    }
}
